package com.bs.service;

import com.bs.domain.AlertSub;
import com.bs.domain.AlertType;
import com.bs.domain.AlertUser;
import com.bs.repository.AlertTypeRepository;
import com.bs.repository.AlertUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by wujian
 * Date: 2017-12-08
 * Time: 15:11
 */
@Service
@Transactional
public class AlertUserService {
    @Autowired
    private AlertUserRepository alertUserRepository;

    public List<AlertUser> query(AlertUser alertUser){
        return alertUserRepository.findAll(where(alertUser));
    }

    public void save(AlertUser alertUser){
        alertUserRepository.save(alertUser);
    }

    public void delete(AlertUser alertUser){
        alertUserRepository.delete(alertUser);
    }

    /**
     * 条件查询时动态组装条件
     */
    private Specification<AlertUser> where(AlertUser alertUser) {
        return new Specification<AlertUser>() {
            @Override
            public Predicate toPredicate(Root<AlertUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<Predicate>();

                if (alertUser.getUserId() != null && !alertUser.getUserId().equals("")) {
                    predicates.add(cb.like(root.<String>get("userId"), "%" + alertUser.getUserId() + "%"));
                }
                if (alertUser.getUserName() != null && !alertUser.getUserName().equals("")) {
                    predicates.add(cb.like(root.<String>get("userName"), "%" + alertUser.getUserName() + "%"));
                }
                return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
            }
        };
    }
}
